import React, { useRef } from 'react';
import { Modal, Form, Input, Select, Row, Col, Divider, Button, InputNumber } from 'antd';
import { DeleteOutlined, PlusOutlined } from '@ant-design/icons';
import type { ApiMapper, ApiParamInfo } from '../txs/types'; // 假设有类型定义文件
import MonacoEditor from "@/pages/component/MonacoEditor";
import { getObject, toast, requestBody, apis } from "@/service/common";


// 响应类型选项
const responseTypeOptions = [
    { label: 'LIST', value: 0 },
    { label: 'JSON', value: 1 },
    { label: 'PAGE', value: 2 },
];

// 参数类型选项
const paramTypeOptions = [
    { label: 'List<String>', value: "array_string" },
    { label: 'List<Double>', value: "array_double" },
    { label: 'List<Integer>', value: "array_int" },
    { label: 'String', value: "string" },
    { label: 'Integer', value: "integer" },
    { label: 'Double', value: "Double" },
];

interface ApiMapperModalProps {
    visible: boolean;
    onCancel: () => void;
    onOk: (values: Partial<ApiMapper>) => void;
    initialValues?: Partial<ApiMapper>;
    confirmLoading?: boolean;
}

const defaultCode = `<select id="select1" resultType="map">
    SELECT * FROM spatial_ref_sys WHERE srid=#{id}
</select>`;

const pageFields: ApiParamInfo[] = [
    { name: "每页大小", code: "pageSize", datatype: "integer", required: true, example: 10 },
    { name: "页码", code: "pageNum", datatype: "integer", required: true, example: 1 }
]

export const ApiMapperModal: React.FC<ApiMapperModalProps> = ({
    visible,
    onCancel,
    onOk,
    initialValues,
    confirmLoading,
}) => {
    const [form] = Form.useForm();
    const [result, setResult] = React.useState<string>('{}')
    const [showPage, setShowPage] = React.useState<boolean>(false)



    function extractVariables(sql: string): string[] {
        // 匹配 #{...} 或 ${...}，非贪婪模式匹配中间内容
        const regex = /[#\$]\{(.*?)\}/g;
        const vars = new Set<string>();
        let match;
        while ((match = regex.exec(sql)) !== null) {
            if (match[1]) {
                vars.add(match[1].trim());
            }
        }
        return Array.from(vars);
    }

    const autoParamInfos = (paramsform, fields, add) => {
        const mapperSql = form.getFieldValue("mapperSql")
        // 确保最新
        const paramInfos = paramsform.getFieldValue("paramInfos") ? paramsform.getFieldValue("paramInfos") : [];

        const extractedVariables = extractVariables(mapperSql)


        extractedVariables.filter(v => !paramInfos.find(p => p.code === v)).forEach(v => {
            add({
                name: v,
                code: v,
                datatype: "string",
                required: true,
                example: null,
            });
        });

        setPageField(form.getFieldValue("responseType") === 2)

    }

    function getSelectInnerContent(xml: string): string {
        // 解析 XML 字符串
        const parser = new DOMParser();
        const doc = parser.parseFromString(xml, "application/xml");
        const selectNode = doc.querySelector("select");
        if (selectNode) {
            // 获取 select 标签内的文本内容（包括换行和空格）
            return selectNode.innerHTML || "";
        }
        return xml;
    }

    const onFinish = async (mode: string) => {
        try {
            console.log(form.getFieldsValue());

            const values = await form.validateFields();
            const params = values.paramInfos ? values.paramInfos : [];
            const paramInfos = params.map(p => { return { ...p } }).map(p => {
                try {
                    if (p.datatype.includes('array')) {
                        p.example = JSON.parse(p.example)
                    } else if (p.datatype === 'integer') {
                        p.example = parseInt(p.example)
                    } else if (p.datatype === 'Double') {
                        p.example = parseFloat(p.example)
                    }
                } catch (error) {

                }
                return { ...p };
            });


            form.setFieldValue("paramInfos", paramInfos);

            if (mode === "save") {
                form.submit()
            } else {

                requestBody({ url: apis.apiServer.mapperTest, data: { ...values, paramInfos } })
                    .then((data) => {
                        toast.success("测试成功");
                        setResult(JSON.stringify(data, null, 2));
                    }).catch(error => {
                        setResult(JSON.stringify(error, null, 2));
                    });
            }

        } catch (error) {
            console.error('测试接口失败:', error);
        }
    };

    // 禁用参数编辑分页框
    const disaParam = (index: number, name: string): boolean => {
        const disaCode = ["pageSize", "pageNum"]
        const disaField = ["code", "name", "datatype", "required"]
        const paramInfos = form.getFieldValue("paramInfos")
        if (typeof index === "number") {
            const p = paramInfos[index]
            if (disaCode.includes(p.code) && disaField.includes(name)) {
                return true
            }
        }
        return false
    }

    // 设置分页字段 set_remove:设置(true)或移除(false)
    const setPageField = (setOrremove: boolean = true) => {
        const paramInfos: ApiParamInfo[] = form.getFieldValue("paramInfos") ? form.getFieldValue("paramInfos") : []
        let paramInfosNew: ApiParamInfo[] = []
        if (setOrremove) {

            if (!paramInfos.find(p => p.code === "pageSize")) {
                paramInfosNew.push({ name: "每页大小", code: "pageSize", datatype: "integer", required: true, example: 10 })
            }
            if (!paramInfos.find(p => p.code === "pageNum")) {
                paramInfosNew.push({ name: "页码", code: "pageNum", datatype: "integer", required: true, example: 1 })
            }
            paramInfosNew = [...paramInfosNew, ...paramInfos]

        } else {
            paramInfosNew = paramInfos.filter(p => !["pageSize", "pageNum"].includes(p.code))
        }
        form.setFieldValue("paramInfos", paramInfosNew)
    }

    React.useEffect(() => {
        if (visible) {
            form.resetFields();
            form.setFieldValue("mapperSql", defaultCode);
            setResult("{}")
            if (initialValues) {
                form.setFieldsValue(initialValues);
            }
        }
    }, [visible, initialValues, form]);

    return (
        <Modal
            title={initialValues?.id ? '编辑Mapper' : '添加Mapper'}
            visible={visible}
            onOk={() => onFinish("save")}
            onCancel={onCancel}
            okText="保存"
            cancelText="取消"
            width="100%"
            bodyStyle={{ height: '85vh', padding: 0 }}
            style={{ top: 0, padding: 0 }}
            destroyOnClose
            confirmLoading={confirmLoading}
            maskClosable={false}
        >
            <div className='flex h-full' style={{ gap: '16px', padding: '16px' }}>
                <div style={{ width: '60%', overflowY: 'auto', paddingRight: '8px' }}>
                    <Form
                        form={form}
                        // layout="vertical"
                        onFinish={onOk}
                        size="small"

                    >
                        <Row gutter={16}>
                            <Col span={10}>
                                <Form.Item
                                    label="名称"
                                    name="name"
                                    rules={[{ required: true, message: '请输入名称' }]}
                                >
                                    <Input placeholder="例如: 用户详情查询" />
                                </Form.Item>
                            </Col>
                            <Col span={10}>
                                <Form.Item
                                    label="编码"
                                    name="code"
                                    rules={[{ required: true, message: '请输入编码' }]}
                                >
                                    <Input placeholder="例如: userDetail" />
                                </Form.Item>
                            </Col>
                        </Row>
                        <Row gutter={16}>
                            <Col span={10}>
                                <Form.Item
                                    label="响应类型"
                                    name="responseType"
                                    rules={[{ required: true, message: '请选择响应类型' }]}
                                >
                                    <Select options={responseTypeOptions} placeholder="请选择响应类型" onSelect={(val) => {
                                        setPageField(val === 2)
                                    }} />
                                </Form.Item>
                            </Col>
                        </Row>

                        <Form.Item
                            label="SQL语句"
                            name="mapperSql"
                            rules={[{ required: true, message: '请输入SQL语句' }]}
                        >
                            <MonacoEditor
                                height="200px"
                                language="xml"
                                onChange={(value) => form.setFieldValue('mapperSql', value)}
                                theme="vs-dark"
                                editorOptions={{ automaticLayout: true }}
                            />
                        </Form.Item>
                        <Divider orientation="left">参数配置</Divider>
                        <Form.List name="paramInfos">
                            {(fields, { add, remove }) => (
                                <>
                                    <div className='flex  gap-2 mb-2 w-[50%]'>
                                        <Button
                                            color="primary" variant="solid"
                                            onClick={() => add()}
                                            icon={<PlusOutlined />}
                                        >
                                            添加参数
                                        </Button>
                                        <Button
                                            color="yellow" variant="solid"
                                            onClick={() => autoParamInfos(form, fields, add)}
                                        >
                                            自动生成
                                        </Button>
                                        <Button
                                            color="lime" variant="solid"
                                            onClick={() => onFinish("test")}
                                        >
                                            测试接口
                                        </Button>
                                    </div>
                                    {fields.map(({ key, name, ...restField }) => (
                                        <Row gutter={16} key={key} style={{ marginBottom: 8 }}>
                                            <Col span={4}>
                                                <Form.Item
                                                    {...restField}
                                                    name={[name, 'name']}
                                                    rules={[{ required: true, message: '参数名必填' }]}
                                                >
                                                    <Input placeholder="参数名" disabled={disaParam(name, 'name')} />
                                                </Form.Item>
                                            </Col>
                                            <Col span={4}>
                                                <Form.Item
                                                    {...restField}
                                                    name={[name, 'code']}
                                                    rules={[{ required: true, message: '参数编码必填' }]}
                                                >
                                                    <Input placeholder="参数编码" disabled={disaParam(name, 'code')} />
                                                </Form.Item>
                                            </Col>
                                            <Col span={4}>
                                                <Form.Item
                                                    {...restField}
                                                    name={[name, 'datatype']}
                                                    rules={[{ required: true, message: '请选择参数类型' }]}
                                                >
                                                    <Select options={paramTypeOptions} placeholder="类型" disabled={disaParam(name, 'required')} />
                                                </Form.Item>
                                            </Col>
                                            <Col span={3}>
                                                <Form.Item
                                                    {...restField}
                                                    name={[name, 'required']}
                                                    valuePropName="checked"
                                                >
                                                    <Select disabled={disaParam(name, 'required')}>
                                                        <Select.Option value={true}>必填</Select.Option>
                                                        <Select.Option value={false}>可选</Select.Option>
                                                    </Select>
                                                </Form.Item>
                                            </Col>
                                            <Col span={7}>
                                                <Form.Item
                                                    {...restField}
                                                    name={[name, 'example']}
                                                >
                                                    <Input placeholder="示例" />
                                                </Form.Item>
                                            </Col>
                                            <Col span={2}>
                                                <Button
                                                    type="text"
                                                    danger
                                                    onClick={() => {
                                                        console.log(fields);
                                                        remove(name)
                                                    }}
                                                    icon={<DeleteOutlined />}
                                                />
                                            </Col>
                                        </Row>
                                    ))}
                                </>
                            )}
                        </Form.List>
                    </Form>
                </div>
                <div style={{ width: '40%', height: '100%' }}>
                    <label >响应结果</label>
                    <MonacoEditor
                        height="90%"
                        language="json"
                        onChange={(value: any) => {
                            setResult(value)

                        }}
                        value={result}
                        editorOptions={{ automaticLayout: true }}
                    />
                </div>
            </div>

        </Modal>
    );
};
